package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import util.IdWorker;

import java.util.Date;
import java.util.List;

@Service
public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;

    /**
     * 查询全部记录
     *
     * @return
     */
    public List<Spit> findAll() {
        return spitDao.findAll();
    }

    /**
     * 根据主键查询实体
     *
     * @param id
     * @return
     */
    public Spit findById(String id) {
        Spit spit = spitDao.findById(id).get();
        return spit;
    }

    /**
     * 增加
     *
     * @param spit
     */
    public void add(Spit spit) {
        spit.set_id(idWorker.nextId() + ""); //主键值
        spit.setThumbup(0);//点赞
        spit.setVisits(0);//访问量
        spit.setState("1");//状态
        spit.setShare(0);//分享量
        spit.setPublishtime(new Date());//发布时间
        spit.setComment(0);//回复量

        if (!StringUtils.isEmpty(spit.getParentid())) {
            //该吐槽是其他吐槽的回复 => 其他吐槽的回复量加1
            //根据id查询
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));//添加条件
            //修改thumbup值为原有值+1
            Update update = new Update();
            update.inc("comment", 1);

            mongoTemplate.updateFirst(query, update, "spit");

        }
        spitDao.save(spit);
    }

    /**
     * 修改
     *
     * @param spit
     */
    public void update(Spit spit) {
        spitDao.save(spit);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        spitDao.deleteById(id);
    }

    //根据父级id分页查询吐槽
    public Page<Spit> findByParentId(String parentId, Integer page, Integer size) {
        return spitDao.findByParentid(parentId, PageRequest.of(page - 1, size));
    }

    @Autowired
    private MongoTemplate mongoTemplate;

    //点赞吐槽
    public void thumbup(String spitId) {
        //根据id查询
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(spitId));//添加条件
        //修改thumbup值为原有值+1
        Update update = new Update();
        update.inc("thumbup", 1);

        mongoTemplate.updateFirst(query, update, "spit");

    }
}